package com.exampleyyy.demoyyy.controller;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.exampleyyy.demoyyy.ServiceJieKou.UserServiceJieKou;
import com.exampleyyy.demoyyy.ShiTi.User;
import com.exampleyyy.demoyyy.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.*;
import com.aliyuncs.profile.DefaultProfile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Random;

@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {
    @PostMapping("/sendMsg")
    public R<Object> sendMsg(@RequestBody User user, HttpSession session) {
        log.info("获取前端的手机号 = " + user.getPhone());
        //调用阿里云短信服务api接口代码，发送一条短信
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou","LTAI5tK5hM3iG2CKBDkyM7vM","pb3f8pqc3AaLUlJkTIJ1bRjmr1JVfa");
        // 实例化客户端对象
        IAcsClient client = new DefaultAcsClient(profile);
        // 实例化请求对象
        SendSmsRequest request = new SendSmsRequest();
        // 设置要发送的手机号
        request.setPhoneNumbers(user.getPhone());
        // 设置短信签名名称
        request.setSignName("阿里云短信测试");
        // 设置阿里云模板编码
        request.setTemplateCode("SMS_154950909");
        // 3.生成随机验证码
        Integer param;
        param = new Random().nextInt(999999);//生成随机数，最大为999999
        if (param < 100000){
            param = param + 100000;//保证随机数为6位数
        }
        log.info("生成的随机验证码 = " + param);
        request.setTemplateParam("{\"code\":\""+param+"\"}");
        session.setAttribute(user.getPhone(), param);
        try {
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(JSON.toJSONString(response));
            // 打印您需要的返回值，此处打印的是此次请求的 RequestId
            System.out.println(response.getRequestId());
            log.info("短信发送成功");
        }catch (ServerException e) {
            e.printStackTrace();
        }catch (ClientException e) {
            //打印错误码
            System.out.println("ErrCode:" + e.getErrCode());
            //打印错误信息
            System.out.println("ErrMsg:" + e.getErrMsg());
            //打印RequestId
            System.out.println("RequestId:" + e.getRequestId());
        }
        return R.success(1, "发送成功", null);
    }
    @Autowired
    private UserServiceJieKou FuWuUserJieKou;
    /**
     * 处理用户登录请求
     *
     * @param QianDuanMa 包含用户手机号和验证码的前端传入数据
     * @param session 用于存储和检索会话信息
     * @return 返回登录结果，包括状态码和消息
     */
    @PostMapping("/login")
    public R<Object> login(@RequestBody Map QianDuanMa, HttpSession session) {
        // 从前端传入的数据中获取手机号和验证码
        String QDphone = QianDuanMa.get("phone").toString();
        String QDcode = QianDuanMa.get("code").toString();
        // 记录前端传来的手机号和验证码信息
        log.info("前端传来的手机号 = " + QDphone + "前端传来的验证码 = " + QDcode);
        // 从后端存储中获取与手机号关联的验证码
        Object HTcode = session.getAttribute(QDphone);
        // 记录后端存储的验证码信息
        log.info("后端存储的验证码 = " + HTcode.toString());
        // 比较前端传来的验证码和后端存储的验证码是否一致
        if (HTcode.toString().equals(QDcode)){
            log.info("验证码正确");

            // 创建查询对象，用于查询用户是否已注册
            LambdaQueryWrapper<User> chaxunduixiang = new LambdaQueryWrapper<>();
            chaxunduixiang.eq(User::getPhone, QDphone);
            // 查询是否已注册
            User user = FuWuUserJieKou.getOne(chaxunduixiang);
            if (user != null){
                // 用户已注册，存储用户ID到会话
                session.setAttribute("用户信息ID", user.getId());
                // 返回登录成功信息
                return R.success(1, "登录成功", null);
            } else {
                // 验证码验证成功后，准备将用户信息存入数据库
                User user1 = new User();
                user1.setPhone(QDphone);
                user1.setStatus("1");
                user1.setAvatar("默认头像");
                // 保存用户信息到数据库
                FuWuUserJieKou.save(user1);
                // 存储新用户ID到会话
                session.setAttribute("用户信息ID", user1.getId());
            }
            // 返回登录成功信息
            return R.success(1, "登录成功", null);
        }
        // 验证码不匹配时，返回错误信息
        return R.error(0, "验证码错误", null);
    }
    @PostMapping("/loginout")
    public R<Object> loginout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return R.success(1, "退出成功", null);
    }
}